package com.example.choupaiapp.main.activity.mine;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ActivityManager;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.MainActivity;
import com.example.choupaiapp.main.bean.InviteTopBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.VersionBean;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.WXShareUtil;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.example.choupaiapp.main.view.DownloadProgressButton;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.db.DownloadManager;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by ASUS on 2019/10/31.
 */

public class SettingActivity extends CommonActivity implements XExecutor.OnAllTaskEndListener, WbShareCallback, WechatCallBack {

    @BindView(R.id.message_switch)
    ImageView messageSwitch;
    @BindView(R.id.version_num)
    TextView versionNum;
    private OkDownload okDownload;
    private List<DownloadTask> values;
    private DownloadTask task;
    private File mFile;
    private Tencent mTencent;

    private UserInfoBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
    }

    @Override
    protected void initView() {
        setTitle("设置");
        userInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");
        versionNum.setText(getAppVersionName());
    }

    @Override
    protected void initData() {
        if (userInfoBean.getUser().getIsPush() == 0) {
            messageSwitch.setImageResource(R.mipmap.switch_open);
        } else {
            messageSwitch.setImageResource(R.mipmap.switch_close);
        }
    }

//    @Override
    @OnClick({R.id.change_info, R.id.message, R.id.safe, R.id.secret, R.id.version, R.id.feed_back, R.id.business, R.id.share, R.id.logout, R.id.about})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.change_info:
                startActivity(MineInfoActivity.class);
                break;
            case R.id.message:
                if (userInfoBean.getUser().getIsPush() == 0) {
                    openPush(1);
                    messageSwitch.setImageResource(R.mipmap.switch_close);
                    showImageToas("已为您关闭了消息推送");
                } else {
                    openPush(0);
                    messageSwitch.setImageResource(R.mipmap.switch_open);
                    showToast("您已开启消息推送");
                }
                break;
            case R.id.safe:
                startActivity(SafeCenterActivity.class);
                break;
            case R.id.secret:
                startActivity(SecretActivity.class);
                break;
            case R.id.version:
                showToast("正在检查新版本...");
                okDownload = OkDownload.getInstance();
                okDownload.setFolder(Environment.getExternalStorageDirectory() + File.separator + "choupai_apk");
                okDownload.getThreadPool().setCorePoolSize(3);
                okDownload.addOnAllTaskEndListener(this);
                values = OkDownload.restore(DownloadManager.getInstance().getDownloading());

                finalOkGo.request(RequestType.POST, Url.APP_VERSION_UPDATE, null, Url.APP_VERSION_UPDATE, new Callback<VersionBean>() {
                    @Override
                    public void onSuccess(VersionBean versionBean) {
                        if (versionBean.getCode() == Contacts.SUCCESS) {
                            if (!versionBean.getVersions().getAndroidVersions().equals(getAppVersionCode() + "")) {
                                DialogUtil.getInstance().showCenterDialog(context, R.layout.dialog_update);
                                LinearLayout dialog_update = (LinearLayout) DialogUtil.getInstance().dialog_center_layout;
                                TextView update_msg = dialog_update.findViewById(R.id.update_msg);
                                update_msg.setText(versionBean.getVersions().getContent());
                                TextView update = dialog_update.findViewById(R.id.update);
                                DownloadProgressButton progressBar = dialog_update.findViewById(R.id.progressBar);
                                update.setOnClickListener(view -> {
                                    if (Utils.isDoubleClick()) {
                                        return;
                                    }
                                    File file = new File(Environment.getExternalStorageDirectory() +
                                            File.separator + "choupai_apk" + File.separator +
                                            versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/")));
                                    if (OkDownload.getInstance().hasTask(versionBean.getVersions().getAndroidVersions())
                                            && file.exists()) {
                                        //存在我们就获取任务继续下载
                                        task = okDownload.getInstance().getTask(versionBean.getVersions().getAndroidVersions()).
                                                fileName(versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/")));
                                    } else {
                                        //不存在就移除任务 创建新任务重新下载
                                        OkDownload.getInstance().removeTask(versionBean.getVersions().getAndroidVersions());

                                        GetRequest<File> request = OkGo.<File>get(versionBean.getVersions().getUrl());
                                        task = OkDownload.request(versionBean.getVersions().getAndroidVersions(), request).fileName(versionBean.getVersions().getUrl().substring(versionBean.getVersions().getUrl().lastIndexOf("/"))).save();
                                    }

                                    task.register(new DownloadListener(versionBean.getVersions().getAndroidVersions()) {
                                        @Override
                                        public void onStart(Progress progress) {
                                            progressBar.setVisibility(View.VISIBLE);
                                            progressBar.setState(DownloadProgressButton.STATE_DOWNLOADING);
                                        }

                                        @Override
                                        public void onProgress(Progress progress) {
                                            progressBar.setMaxProgress(Integer.parseInt(progress.totalSize + ""));
                                            progressBar.setProgress(Float.parseFloat(progress.currentSize + ""));
                                            progressBar.postInvalidate();
                                        }

                                        @Override
                                        public void onError(Progress progress) {
                                            Throwable throwable = progress.exception;
                                            if (throwable != null) {
                                                if (throwable instanceof SocketException) {
                                                    showToast("网络开小差了...");
                                                    cancleDownload(throwable);
                                                } else if (throwable instanceof UnknownHostException) {
                                                    showToast("无网络");
                                                    cancleDownload(throwable);
                                                } else {
                                                    OkDownload.getInstance().removeTask(versionBean.getVersions().getAndroidVersions());
                                                    cancleDownload(throwable);
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFinish(File file, Progress progress) {
                                            OkDownload.getInstance().removeTask(versionBean.getVersions().getAndroidVersions());
                                            task.unRegister(this);
                                            DialogUtil.getInstance().dialog_center.dismiss();
                                            installApk(file);
                                        }

                                        @Override
                                        public void onRemove(Progress progress) {

                                        }
                                    });
                                    task.save();
                                    task.start();
                                });
                            } else {
                                showToast("当前为最新版本");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });


                break;
            case R.id.feed_back:
                Bundle bundle = new Bundle();
                bundle.putString("flag", "feed");
                startActivity(FeedBackActivity.class);
                break;
            case R.id.business:
                call(Config.BUSINESS_PHONE);
                break;
            case R.id.share:
                showDialog(context, null);
                finalOkGo.requestHead(RequestType.POSTHEAD, Url.INVITE_TOP_INFO, null, Url.INVITE_TOP_INFO, new Callback<InviteTopBean>() {
                    @Override
                    public void onSuccess(InviteTopBean inviteTopBean) {
                        dismissDialog();
                        if (inviteTopBean.getCode() == Contacts.SUCCESS) {
                            showShareDialog(inviteTopBean.getInviteUrl() + "?inviteCode=" + userInfoBean.getUser().getInviteCode(),inviteTopBean);
                        } else {
                            if (inviteTopBean.getCode() == Contacts.TOKEN_EMPTY) {
                            }else{
                                showImageToas(inviteTopBean.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
                break;
            case R.id.logout:
                showDialogs();
                break;
            case R.id.about:
                startActivity(AboutActivity.class);
                break;
        }
    }


    private void showShareDialog(String url, InviteTopBean inviteTopBean) {

        DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_share);
        LinearLayout dialog_share = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
        dialog_share.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_bottom.dismiss();
            }
        });

        dialog_share.findViewById(R.id.share_wechat).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(SettingActivity.this);

            wxShareUtil.share(url,
                    inviteTopBean.getInviteTitle(),
                    inviteTopBean.getInviteDetails(),
                    "", wxShareUtil.SHARETOFRIEND);
            MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        });

        dialog_share.findViewById(R.id.share_wechat_friend).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(SettingActivity.this);
            wxShareUtil.share(url,
                    inviteTopBean.getInviteTitle(),
                    inviteTopBean.getInviteDetails(),
                    "", wxShareUtil.SHARETOPYQ);
            MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        });

        dialog_share.findViewById(R.id.share_qq).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, ContextUtil.getContext());
            Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, inviteTopBean.getInviteTitle());
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, inviteTopBean.getInviteDetails());
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
            mTencent.shareToQQ(SettingActivity.this, params, new BaseUiListener());
            shareSuccess();
        });

        dialog_share.findViewById(R.id.share_qq_space).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, context);
            Bundle params = new Bundle();
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, inviteTopBean.getInviteTitle() + "\n" + inviteTopBean.getInviteDetails());//选填
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "");
            params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, "");
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());
            mTencent.shareToQzone(SettingActivity.this, params, new BaseUiListener());
            shareSuccess();
        });

        dialog_share.findViewById(R.id.share_weibo).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WbSdk.install(ContextUtil.getContext(), new AuthInfo(ContextUtil.getContext(), Config.SINA_APP_KEY, Config.REDIRECT_URL, ""));
            WbShareHandler shareHandler = new WbShareHandler(SettingActivity.this);
            shareHandler.registerApp();
            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
            weiboMessage.textObject = getTextObj(url, inviteTopBean.getInviteTitle() + "\n" + inviteTopBean.getInviteDetails());
            shareHandler.shareMessage(weiboMessage, false);
            shareSuccess();
        });

        dialog_share.findViewById(R.id.copy_link).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
            ClipData clipData = ClipData.newPlainText(null, url);
            // 把数据集设置（复制）到剪贴板
            clipboard.setPrimaryClip(clipData);
            showToast("链接已复制");
            MobclickAgent.onEvent(ContextUtil.getContext(), "invitationID");
        });

        dialog_share.findViewById(R.id.copy_text).setVisibility(View.INVISIBLE);

        dialog_share.findViewById(R.id.black_list).setVisibility(View.INVISIBLE);
        dialog_share.findViewById(R.id.report).setVisibility(View.INVISIBLE);

    }

    @Override
    public void onWbShareSuccess() {
//        showToast("分享成功");
    }

    @Override
    public void onWbShareCancel() {
//        showImageToas("分享取消");
    }

    @Override
    public void onWbShareFail() {
//        showImageToas("分享失败");
    }

    @Override
    public void callBack(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                showToast("分享成功");
                shareSuccess();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                showImageToas("分享取消");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                showImageToas("分享被拒绝");
                break;
            default:
                showImageToas("分享返回");
                break;
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
//            showToast("分享成功");
        }

        @Override
        public void onError(UiError uiError) {
//            showImageToas("分享失败");
        }

        @Override
        public void onCancel() {
//            showImageToas("分享取消");
        }
    }


    private TextObject getTextObj(String url, String title) {
        TextObject textObject = new TextObject();
        textObject.text = title + "\n" + url;
        textObject.title = title;
        textObject.actionUrl = url;
        return textObject;
    }

    private void shareSuccess() {
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.SHARE_FRIEND_SUCCESS, null, Url.SHARE_FRIEND_SUCCESS, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {

                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }
        });
    }

    private void cancleDownload(Throwable throwable) {
        DialogUtil.getInstance().dialog_center.dismiss();
        showImageToas("下载失败，可能导致应用不能使用，请尽快更新");
        throwable.printStackTrace();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (okDownload != null) {
            okDownload.removeOnAllTaskEndListener(this);
        }
    }

    private void openPush(int isPush) {
        showDialog(context, "修改中...");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("isPush", isPush);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                dismissDialog();
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    userInfoBean.getUser().setIsPush(isPush);
                    EventBus.getDefault().post("refresh_mine");
                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    }else{
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    public void showDialogs() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //    设置Title的图标
        //    设置Title的内容
        builder.setTitle("消息提示");
        //    设置Content来显示一个信息
        builder.setMessage("确定退出登录？");

        builder.setPositiveButton("确定", (dialog, which) -> {

            dialog.dismiss();
            AccessTokenKeeper.clear(ContextUtil.getContext());
            EMClient.getInstance().logout(true);
            SharedPreferencesHelp.remove("token");
            SharedPreferencesHelp.remove("userInfo");
            JPushInterface.deleteAlias(context, 0);
            MobclickAgent.onProfileSignOff();
            ActivityManager.getActivityManager().popAllActivity();
            startFinishActivity(MainActivity.class);

        });
        //    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    @Override
    public void onAllTaskEnd() {
        showToast("下载完成");
    }

    protected void installApk(File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //是否有安装位置来源的权限
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Uri apkUri = FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".fileprovider", file);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                } else {
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri uri = Uri.fromFile(file);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                }
                startActivity(intent);
            } else {
                mFile = file;
                Uri packageUri = Uri.parse("package:" + getApplicationContext().getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                startActivityForResult(intent, 10086);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".fileprovider", file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromFile(file);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mTencent != null) {
            mTencent.onActivityResult(requestCode, resultCode, data);
        }
        if (requestCode == 10086) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".fileprovider", mFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri uri = Uri.fromFile(mFile);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }

    }
}
